<template>
  <div class="order-container">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.number"
            placeholder="请输入订单号"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择订单状态"
            clearable
            style="width: 180px;"
            @change="handleSearch"
          >
            <el-option label="待付款" :value="1"></el-option>
            <el-option label="待配送" :value="2"></el-option>
            <el-option label="配送中" :value="3"></el-option>
            <el-option label="已完成" :value="4"></el-option>
            <el-option label="已取消" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="orderList" style="width: 100%" border>
      <el-table-column type="expand">
        <template #default="props">
          <div v-if="props.row.orderDetails && props.row.orderDetails.length > 0">
            <el-table :data="props.row.orderDetails" style="width: 100%" border class="items-table">
              <el-table-column prop="dishName" label="菜品名称" width="200"></el-table-column>
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">
                  ¥{{ parseFloat(scope.row.price).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="number" label="数量" width="100"></el-table-column>
              <el-table-column label="小计" width="100">
                <template #default="scope">
                  ¥{{ (parseFloat(scope.row.price) * parseInt(scope.row.number)).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-details">暂无订单详情</div>
        </template>
      </el-table-column>
      <el-table-column prop="number" label="订单号" width="180"></el-table-column>
      <el-table-column prop="userName" label="用户" width="120"></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
      <el-table-column prop="amount" label="金额" width="100">
        <template #default="scope">
          ¥{{ parseFloat(scope.row.amount).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)" class="status-tag">
            {{ getOrderStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.orderTime) || '暂无数据' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            type="danger"
            size="small"
            @click="cancelOrder(scope.row)"
          >
            取消
          </el-button>
          <el-button
            v-if="scope.row.status === 2"
            type="success"
            size="small"
            @click="deliveryOrder(scope.row)"
          >
            配送
          </el-button>
          <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0) // 初始化为0，避免闪烁

// 搜索表单
const searchForm = reactive({
  number: '',
  status: '',
  dateRange: [] as string[]
})

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.timeout = 30000 // 增加超时时间到30秒
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.withCredentials = true // 允许跨域请求携带cookie

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    // 确保请求头包含Content-Type
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json'
    }

    // 打印请求信息，帮助调试
    console.log(`发送${config.method?.toUpperCase()}请求到: ${config.url}`, config.params || config.data)

    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 打印响应数据，帮助调试
    console.log(`接收到来自${response.config.url}的响应:`, response.data)
    return response
  },
  error => {
    // 详细记录错误信息
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('API响应错误:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data,
        url: error.config?.url,
        method: error.config?.method
      })

      if (error.response.status === 500) {
        ElMessage.error('服务器内部错误，请联系管理员')
      } else if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        // 可以在这里添加重定向到登录页的逻辑
      } else {
        ElMessage.error(`请求失败: ${error.response.data.msg || error.response.statusText}`)
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      console.error('未收到响应:', error.request)
      ElMessage.error('服务器无响应，请检查网络连接或联系管理员')
    } else {
      // 请求配置出错
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求错误: ${error.message}`)
    }

    return Promise.reject(error)
  }
)

// 订单列表
const orderList = ref([])

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 1: return '待付款'
    case 2: return '待配送'
    case 3: return '配送中'
    case 4: return '已完成'
    case 5: return '已取消'
    default: return '未知状态'
  }
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case 1: return 'warning' // 将"待付款/待接单"状态改为黄色(warning)
    case 2: return 'primary' // 将"待配送"状态改为蓝色(primary)
    case 3: return 'success'
    case 4: return 'success' // 将"已完成"状态改为绿色(success)
    case 5: return 'danger'
    default: return 'info'
  }
}

// 格式化日期时间为更友好的格式
const formatDateTime = (dateTimeStr: string | null | undefined): string => {
  if (!dateTimeStr) return '暂无数据'

  try {
    const date = new Date(dateTimeStr)

    // 获取当前日期
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const yesterday = new Date(today)
    yesterday.setDate(yesterday.getDate() - 1)

    // 检查是否是今天
    if (date >= today) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 检查是否是昨天
    if (date >= yesterday && date < today) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 如果是今年的其他日期
    const currentYear = now.getFullYear()
    if (date.getFullYear() === currentYear) {
      return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 如果是其他年份
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateTimeStr // 如果解析失败，返回原始字符串
  }
}

// 从后端获取订单数据
const fetchOrderList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 准备查询参数
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加订单号查询条件
    if (searchForm.number) {
      params.number = searchForm.number
    }

    // 添加订单状态查询条件
    if (searchForm.status !== '') {
      params.status = searchForm.status
    }

    // 添加时间范围查询条件
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.beginTime = `${searchForm.dateRange[0]} 00:00:00`
      params.endTime = `${searchForm.dateRange[1]} 23:59:59`
    }

    console.log('发送查询参数:', params)

    // 调用后端API获取订单列表
    const response = await axios.get('/order/merchantPage', { params })

    if (response.data.code === 1) {
      // 更新订单列表和总数
      orderList.value = response.data.data.records || []
      total.value = response.data.data.total || 0

      // 如果后端没有返回总数，但有返回记录，则使用记录数量作为总数
      if (total.value === 0 && orderList.value.length > 0) {
        total.value = orderList.value.length
      }

      console.log('订单列表数据:', orderList.value)
      console.log('总记录数:', total.value)
    } else {
      ElMessage.error(response.data.msg || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表出错:', error)
    ElMessage.error('获取订单列表失败，请稍后再试')
  } finally {
    loading.close()
  }
}

// 搜索订单
const handleSearch = () => {
  currentPage.value = 1 // 重置为第一页
  fetchOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.number = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentPage.value = 1 // 重置为第一页
  fetchOrderList()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchOrderList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchOrderList()
}

// 接单
const acceptOrder = (order: any) => {
  ElMessageBox.confirm(`确定要接受订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用后端API接单
      const response = await axios.put(`/order/accept/${order.id}`)

      if (response.data.code === 1) {
        ElMessage.success('接单成功')
        setTimeout(() => {
          fetchOrderList() // 重新加载订单列表
        }, 500)
      } else {
        ElMessage.error(response.data.msg || '接单失败')
      }
    } catch (error) {
      console.error('接单出错:', error)
      ElMessage.error('接单失败，请稍后再试')
    } finally {
      loading.close()
    }
  }).catch(() => {})
}

// 查看订单详情
const viewOrderDetail = (order: any) => {
  // 获取订单详情
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  axios.get(`/order/detail/${order.id}`)
    .then(response => {
      if (response.data.code === 1) {
        const orderData = response.data.data

        // 构建详情内容
        let detailContent = `
          <div style="text-align: left; margin-bottom: 15px;">
            <p><strong>订单号：</strong>${orderData.number}</p>
            <p><strong>下单时间：</strong>${formatDateTime(orderData.orderTime)}</p>
            <p><strong>用户名：</strong>${orderData.userName || '暂无数据'}</p>
            <p><strong>联系电话：</strong>${orderData.phone || '暂无数据'}</p>
            <p><strong>订单状态：</strong>${getOrderStatusText(orderData.status)}</p>
            <p><strong>订单金额：</strong>¥${parseFloat(orderData.amount).toFixed(2)}</p>
          </div>
        `

        // 如果有订单详情，添加菜品列表
        if (orderData.orderDetails && orderData.orderDetails.length > 0) {
          detailContent += '<div style="margin-top: 15px;"><strong>订单菜品：</strong></div>'
          detailContent += '<table style="width: 100%; border-collapse: collapse; margin-top: 10px;">'
          detailContent += '<tr style="background-color: #f2f2f2;"><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">菜品名称</th><th style="padding: 8px; text-align: center; border: 1px solid #ddd;">单价</th><th style="padding: 8px; text-align: center; border: 1px solid #ddd;">数量</th><th style="padding: 8px; text-align: center; border: 1px solid #ddd;">小计</th></tr>'

          orderData.orderDetails.forEach((item: any) => {
            // 确保价格和数量是数字类型
            const price = parseFloat(item.price) || 0
            const number = parseInt(item.number) || 0
            const subtotal = (price * number).toFixed(2)

            detailContent += `
              <tr>
                <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${item.dishName}</td>
                <td style="padding: 8px; text-align: center; border: 1px solid #ddd;">¥${price.toFixed(2)}</td>
                <td style="padding: 8px; text-align: center; border: 1px solid #ddd;">${number}</td>
                <td style="padding: 8px; text-align: center; border: 1px solid #ddd;">¥${subtotal}</td>
              </tr>
            `
          })

          detailContent += '</table>'
        }

        // 显示详情对话框
        ElMessageBox.alert(detailContent, '订单详情', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          customClass: 'order-detail-dialog'
        })
      } else {
        ElMessage.error(response.data.msg || '获取订单详情失败')
      }
    })
    .catch(error => {
      console.error('获取订单详情出错:', error)
      ElMessage.error('获取订单详情失败，请稍后再试')
    })
    .finally(() => {
      loading.close()
    })
}

// 取消订单
const cancelOrder = (order: any) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用后端API取消订单
      const response = await axios.put(`/order/cancel/${order.id}`)

      if (response.data.code === 1) {
        ElMessage.success('订单已取消')
        setTimeout(() => {
          fetchOrderList() // 重新加载订单列表
        }, 500)
      } else {
        ElMessage.error(response.data.msg || '取消失败')
      }
    } catch (error) {
      console.error('取消订单出错:', error)
      ElMessage.error('取消失败，请稍后再试')
    } finally {
      loading.close()
    }
  }).catch(() => {})
}

// 配送订单
const deliveryOrder = (order: any) => {
  ElMessageBox.confirm(`确定要配送订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用后端API配送订单
      const response = await axios.put(`/order/delivery/${order.id}`)

      if (response.data.code === 1) {
        ElMessage.success('订单已开始配送')
        setTimeout(() => {
          fetchOrderList() // 重新加载订单列表
        }, 500)
      } else {
        ElMessage.error(response.data.msg || '配送失败')
      }
    } catch (error) {
      console.error('配送订单出错:', error)
      ElMessage.error('配送失败，请稍后再试')
    } finally {
      loading.close()
    }
  }).catch(() => {})
}

// 组件挂载时加载数据
onMounted(() => {
  // 立即加载数据，不使用延迟
  fetchOrderList()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.items-table {
  margin: 10px;
  background-color: #f9f9f9;
}

.items-table :deep(th) {
  background-color: #eef1f6;
  color: #606266;
  font-weight: 500;
}

.items-table :deep(td) {
  padding: 8px 0;
}

.no-details {
  margin: 20px;
  color: #909399;
  font-size: 14px;
  text-align: center;
}

/* 状态标签样式 */
.status-tag {
  min-width: 80px;
  text-align: center;
  padding: 0 10px;
  font-size: 14px;
  display: inline-block;
}

/* 订单详情对话框样式 */
:deep(.order-detail-dialog) {
  max-width: 600px;
  width: 90%;
}

:deep(.order-detail-dialog .el-message-box__content) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

:deep(.order-detail-dialog .el-message-box__title) {
  font-size: 18px;
  font-weight: bold;
}
</style>
